package com.jvm123.excel.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class CellLocation {

    public static final char DYNAMIC_ROW_MARK = '+';

    private int columnIndex;

    private int rowIndex;

    private String location;

    private int rowOffset = 0;

    public CellLocation(String location) {
        convert(location);
        this.location = location;
    }

    public CellLocation(String location, int rowOffset) {
        this.rowOffset = rowOffset;
        convert(location);
        this.location = location;
    }

    private void convert(String location) {
        if (location == null) {
            return;
        }
        boolean isDynamic = false;
        char[] chars = location.toUpperCase().toCharArray();
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        for (; i < chars.length; i++) {
            if (chars[i] >= 65 && chars[i] <= 90) {
                // 'A' == 65   'Z' == 90
                stack.push(chars[i] - 64);
            } else if (chars[i] == DYNAMIC_ROW_MARK) {
                isDynamic = true;
            } else {
                break;
            }
        }
        // row从0开始计算
        rowIndex = Integer.parseInt(location.substring(i)) - 1;
        if (isDynamic) {
            rowIndex += rowOffset;
        }

        List<Integer> list = new ArrayList<>();
        while (!stack.empty()) {
            list.add(stack.pop());
        }
        for (int j = 0; j < list.size(); j++) {
            columnIndex += list.get(j) * Math.pow(26, j);
        }
        // 索引从0开始
        columnIndex--;
    }

    public int getColumnIndex() {
        return columnIndex;
    }

    public int getRowIndex() {
        return rowIndex;
    }

    public String getLocation() {
        return location;
    }

    //    public static void main(String[] args) {
//        System.out.println('A' + 0); // 65
//        System.out.println('Z' + 0); // 90
//        System.out.println('1' + 0); // 49
//    }

}
